package com.suning.sawp.service.impl.commodity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.common.URL;
import com.suning.framework.dal.client.DalClient;
import com.suning.framework.image.common.RandomUtils;
import com.suning.rsf.consumer.ServiceLocator;
import com.suning.sawp.intf.commodity.BppCommodityService;
import com.suning.sawp.po.commodity.BppCommodityInfo;
import com.suning.sawp.service.util.SCMConfigUtil;
import com.suning.slss.intf.service.qrcode.ShortCodeServiceRsf;
import com.suning.slss.intf.service.qrcode.data.ShortCodeResponse;

/**
 * 
 * 〈大聚会商品处理〉<br>
 * 〈功能详细描述〉
 *
 * @author 12061748
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Service("bppCommodityService")
public class BppCommodityServiceImpl implements BppCommodityService {

    /**
     * 日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(BppCommodityServiceImpl.class);
            
    /**
     * 数字
     */
    private static final int NO_20 = 20;
    private static final int NO_5 = 5;
    private static final int NO_1 = 1;
    private static final int NO_10 = 10;

    /**
     * 短链保存时间
     */
    private static final int SHORT_URL_DAYS = 90;
    
    @Autowired
    DalClient dalClient;

    /**
     * 商品地址
     */
    @Value("#{settingConfig[mSuningUrl]}")
    String mSuningUrl;

    /**
     * 注册地址
     */
    @Value("#{settingConfig[registerUrl]}")
    String registerUrl;

    /**
     * 图片地址
     */
    @Value("#{settingConfig[b2c_image_url]}")
    String b2cImageUrl;
    
    /**
     * 短链RSF服务
     */
    ShortCodeServiceRsf shortCodeServiceRsf = ServiceLocator.getService(
            ShortCodeServiceRsf.class, "ShortCodeServiceRsfImpl");

    /**
     * 保存商品
     */
    @Override
    public void save(BppCommodityInfo bppCommodityInfo) {
        dalClient.persist(bppCommodityInfo);
    }

    /**
     * 判断活动是否存在
     */
    @Override
    public Long judgeIsExsit(String actId) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("actId", actId);
        List<BppCommodityInfo> list = dalClient.queryForList("BPP_COMMODITY.QUERY_COMM_INFO_BY_ACTID", paramMap,
                BppCommodityInfo.class);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0).getId();
        }
        return null;
    }

    /**
     * 更新商品
     */
    @Override
    public void update(BppCommodityInfo bppCommodityInfo) {
        dalClient.merge(bppCommodityInfo);
    }

    /**
     * 查询商品
     */
    @Override
    public List<BppCommodityInfo> getCommodityInfoList(Integer start, Integer limit, String storeSaleCode,
            String staffCode) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        Integer startEx = start;
        Integer limitEx = limit;
        if (startEx == null || startEx < 0) {
            startEx = 0;
        }
        if (limitEx == null || limitEx < 0 || limitEx > NO_20) {
            limitEx = NO_10;
        }
        paramMap.put("start", startEx);
        paramMap.put("limit", limitEx);

        List<BppCommodityInfo> list = dalClient.queryForList("BPP_COMMODITY.QUERY_COMM_INFO", paramMap,
                BppCommodityInfo.class);
        handleCommodityList(storeSaleCode, staffCode, list);
        return list;
    }

    /**
     * 转换商品属性 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param storeSaleCode
     * @param staffCode
     * @param list
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private void handleCommodityList(String storeSaleCode, String staffCode, List<BppCommodityInfo> list) {
        if (CollectionUtils.isNotEmpty(list)) {
            for (BppCommodityInfo info : list) {
                if (StringUtils.isEmpty(info.getPayPrice())) {
                    // 易购价格为空，按照扫码价格来
                    info.setPayPrice(info.getGbPrice());
                }
                info.setCutPrice(
                        String.format("%.2f", Double.valueOf(info.getPayPrice()) - Double.valueOf(info.getGbPrice())));
                StringBuilder url = new StringBuilder();
                StringBuilder mUrl = new StringBuilder(getProductUrl());
                if ("0".equals(info.getMertCode())) {
                    mUrl.append("0000000000/");
                } else {
                    mUrl.append(info.getMertCode()).append("/");
                }
                mUrl.append(info.getCommCode()).append("_0_0.html");
                url.append(mUrl).append("?utm_source=qrcode&utm_medium=07&utm_content=").append(storeSaleCode)
                        .append("&utm_term=0101&utm_campaign=").append(staffCode).append("&adTypeCode=1002&adId=")
                        .append(URL.encode(mUrl.toString())).append("&channeltype=07&store=").append(storeSaleCode).append("_0101_")
                        .append(staffCode);
                info.setDetailUrl(getShortUrl(url.toString()));
                info.setQrcodeUrl(getShortUrl(url.toString()));
                String imageUrl = getImageUrl().replace("?", String.valueOf(RandomUtils.nextInt(NO_5) + NO_1))
                        .replace("{commCode}", info.getCommCode());
                info.setImageUrl(imageUrl);
            }
        }
    }
    
    /**
     * https组装
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private String getProductUrl() {
        // 判断是否是适配开头
        if (mSuningUrl.startsWith("//")) {
            String protocol = SCMConfigUtil.getConfig("request_protocol", "https");
            return protocol + ":" + mSuningUrl;
        }
        return mSuningUrl;
    }
    
    /**
     * https改造组装
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private String getImageUrl() {
        // 判断是否是适配开头
        if (b2cImageUrl.startsWith("//")) {
            String protocol = SCMConfigUtil.getConfig("request_protocol", "https");
            return protocol + ":" + b2cImageUrl;
        }
        return b2cImageUrl;
    }

    /**
     * 删除商品
     */
    @Override
    public void delete(String actId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("actId", actId);
        dalClient.execute("BPP_COMMODITY.DELETEBPPGOODSBYACTID", map);
    }
    
    /**
     * 短链生成
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param url
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private String getShortUrl(String url) {
        try {
            ShortCodeResponse resp = shortCodeServiceRsf.buildShortCode(url, SHORT_URL_DAYS);
            if (null != resp && StringUtils.isNotBlank(resp.getShortUrl())) {
                return resp.getShortUrl();
            }
        } catch (Exception e) {
            LOGGER.error("shortCodeServiceRsf.buildShortCode error.", e);
        }
        return url;
    }
}
